<?php

namespace app\merchant\job;

use app\common\model\Agent;
use app\common\model\Merchant;
use app\common\model\ProfitAccount;
use app\common\model\ProfitList;
use app\common\model\WxOpen;
use think\Log;
use think\queue\Job;
use Wechat\Wxobjopen;
use Weixinpay\Wxtk;

class Fenzhang
{

    public function fire(Job $job, $data)
    {
//        file_put_contents('/data2/html/payos/exelog/test/' . 'task_tpl_card'.date("Y-m-d") . '.txt',  '0-1:' . json_encode($data, JSON_UNESCAPED_UNICODE).PHP_EOL, FILE_APPEND);

        $isJobDone = $this->task_fenzhang($data);
        $job->delete();

        if ($isJobDone) {
            //如果任务执行成功， 记得删除任务
            $job->delete();
            return '完成';
        } else {
            if ($job->attempts() > 3) {
                print("<warn>任务已完成3次!" . "</warn>\n");
                $job->delete();
                // 也可以重新发布这个任务
                //print("<info>Hello Jobmach will be availabe again after 2s."."</info>\n");
                //$job->release(2); //$delay为延迟时间，表示该任务延迟2秒后再执行
            }
        }
    }



    /**
     * 根据消息中的数据进行实际的业务处理
     * @param array|mixed $data 发布任务时自定义的数据
     * @return boolean                 任务执行的结果
     */


    //执行分账
    public function task_fenzhang($data)
    {
        try{
            $Merchant = new Merchant();
            $Agent = new Agent();
            $WxOpen = new WxOpen();
            $map['id'] = $data['mid'];
            $config = $Merchant->where($map)->find();
            $agent = $Agent->where(array('id' => $config['agent']))->find();
            $users = $WxOpen->where(array('id' => $agent['wx_open_id']))->find();
            $userwx = $WxOpen->where(array('id' => $config['wx_open_id']))->find();
            $options = array(
                'appid' => $users['authorizer_appid'], // 填写高级调用功能的app id
                'partnerid' => $agent['partnerid'], // 财付通商户身份标识
                'partnerkey' => $agent['partnerkey'], // 财付通商户权限密钥Key
            );
            $weObj = new Wxobjopen($options);

            $appid = $users['authorizer_appid'];
            $mch_id = $agent['partnerid'];
            $sub_mch_id = $config['sub_mch_id'];
            $sub_appid = $userwx['authorizer_appid'];
            $nonce_str = $weObj->generateNonceStr();
            $fz_trade_no = "FZ" . $data['mid'] . "-" . date('YmdHis') . rand(1000, 9999);

            $transaction_id = $data['orderno'];

            $receivers = $this->profit_account($data['mid'],$data['price']);
            $options['wx_open_id'] = $agent['wx_open_id'];
            $weObj = new Wxtk($options);
            $weObj->setParameter('appid', $appid);
            $weObj->setParameter('sub_appid', $sub_appid);
            $weObj->setParameter('mch_id', $mch_id);
            $weObj->setParameter('sub_mch_id', $sub_mch_id);
            $weObj->setParameter('nonce_str', $nonce_str);
            $weObj->setParameter('out_order_no', $fz_trade_no);
            $weObj->setParameter('transaction_id', $transaction_id);
            $weObj->setParameter('receivers', json_encode($receivers, JSON_UNESCAPED_UNICODE));
            $sss = $weObj->create_fz_xml($agent['partnerkey']);
            $url = 'https://api.mch.weixin.qq.com/secapi/pay/profitsharing';//分账
            $responseXml = $weObj->curl_post_ssl($url, $sss);

            $responseObj = simplexml_load_string($responseXml, 'SimpleXMLElement', LIBXML_NOCDATA);
            $responseArr = ( array )$responseObj;
            $sa_data['fz_trade_no']=$fz_trade_no;
            if ($responseArr['return_code'] == "SUCCESS") {
                if ($responseArr['result_code'] == "SUCCESS") {

                    $sa_data['work_time']=time();
                    $sa_data['work_info']=json_encode($responseArr,JSON_UNESCAPED_UNICODE);
                    $sa_data['status']="Y";
                } else {
                    $sa_data['work_time']=time();
                    $sa_data['work_info']=$responseArr['err_code'] . $responseArr['err_code_des'];
                    $sa_data['status']="E";
                }
            } else {
                $sa_data['work_time']=time();
                $sa_data['work_info']=json_encode($responseArr,JSON_UNESCAPED_UNICODE);
                $sa_data['status']="E";
            }
            $ProfitList=new ProfitList();
            $ProfitList->save($sa_data,['id'=>$data['id']]);
        }catch (\Exception $e){
            Log::write("task_fenzhang:".$e->getMessage() . $e->getFile() . ":" . $e->getLine(),'SysRunErrorLog');
        }
    }

    private function profit_account($mid,$price)
    {
        $ProfitAccount = new ProfitAccount();
        $map['mid'] = $mid;
        $map['status'] = "Y";
        $profitacc = $ProfitAccount->where($map)->select();
        $re=[];
        foreach ($profitacc as $k => $v) {
            if($v['fz_type']=="B"){
                $amount=number_format($v['fz_num']*$price,"2",".","")*100;
            }elseif($v['fz_type']=="G"){
                $amount=$v['fz_num']*100;
            }

            $re[$k]['type']=$v['type'];
            $re[$k]['account']=$v['account'];
            $re[$k]['amount']=$amount;
            $re[$k]['description']=date('Y-m-d')."日分账";
        }
        return $re;

    }


}
